<template>
    <div class="content">
      <el-row :gutter="10">
        <el-col :md="8"  :sm="8" :xs="24">
          <div class="bg-content">
            <el-input
            placeholder="请输入部门名称"
            v-model="filterText">
            </el-input>
            <el-tree
            class="filter-tree"
            :data="treedata"
            :props="defaultProps"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            ref="treedata"
            :default-expanded-keys="defaultExpandedNode"
            node-key="id"
            @node-click="treeNodeSelected"
            highlight-current>
              <span class="custom-tree-node" slot-scope="{node , data }">
                <template v-if="data.children == null">
                  <span><i class="el-icon-document"></i></span>
                  <span>{{node.label}}</span>
                </template>
                <template v-else>
                  <span>{{node.label}}</span>
                </template>
              </span>
            </el-tree>
          </div>
        </el-col>
        <el-col :md="16" :sm="16" :xs="24">
          <div class="bg-content">
              <el-tabs v-model="activeName">
                <el-tab-pane label="基本信息" name="first">
                  <div class="basicdata">
                    <departBasicData ref="departBasicData"></departBasicData>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="用户信息" name="second">
                  <div class="userdata">
                    <div class="search_box">
                      部门角色名称：
                      <el-input type="text" size="medium" placeholder="请输入部门角色" v-model="userDataSearch" class="input_box"></el-input>
                      <el-button type="primary" size="medium" icon="el-icon-search">查询</el-button>
                      <el-button type="primary" size="medium" icon="el-icon-refresh-right">重置</el-button>
                    </div>
                    <departRoleData>
                      <template v-slot:btnSlot>
                        <el-button type="primary" size="medium" icon="el-icon-plus">添加已有用户</el-button>
                        <el-button type="primary" size="medium" icon="el-icon-plus">新建用户</el-button>
                        <el-button size="medium">批量操作<i class="el-icon-arrow-down"></i></el-button>
                      </template>
                    </departRoleData>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="部门角色" name="third">
                  <div class="roledata">
                    <div class="search_box">
                      部门角色名称：
                      <el-input type="text" size="medium" placeholder="请输入部门角色" v-model="roleDataSearch" class="input_box"></el-input>
                      <el-button type="primary" size="medium" icon="el-icon-search" @click="roleSearch()">查询</el-button>
                      <el-button type="primary" size="medium" icon="el-icon-refresh-right" @click="roleReset()">重置</el-button>
                    </div>
                    <departRoleData 
                    :headerData="roleheaderData" 
                    :tableData="roletableData" 
                    :currentPage="pageNo" 
                    :pageSize="pageSize" 
                    :total="total"
                    :tableNodeSelected="tableNodeSelected"
                    @SizeChange="SizeChange"
                    @CurrentPageChange="CurrentPageChange"
                    @getSelection="getSelection"
                    >
                      <template v-slot:btnSlot>
                        <el-button type="primary" size="medium" icon="el-icon-plus" @click="roleAdd()" class="addBtn">新增部门角色</el-button>
                        <el-dropdown @command="tableStatus"  v-show="multipleSelection.length">
                          <el-button>批量操作 <i class="el-icon-arrow-down"></i></el-button>
                          <el-dropdown-menu slot="dropdown" style="width=100px">
                            <el-dropdown-item command="1" class="el-icon-delete">删除</el-dropdown-item>
                          </el-dropdown-menu>
                        </el-dropdown>
                      </template>
                      <template v-slot:handle="{row}">
                        <div>
                          <el-button type="text" class="editBtn" @click="roleEdit(row)">编辑</el-button>
                          <el-dropdown>
                            <span class="el-dropdown-link">
                              更多<i class="el-icon-arrow-down el-icon--right"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                              <el-dropdown-item >
                                <span @click="tableStatus(2,row)">授权</span> 
                              </el-dropdown-item>
                              <el-popconfirm title="确定删除吗？" @confirm="tableStatus(3,row)">
                                <el-dropdown-item slot="reference">
                                  <span>删除</span> 
                                </el-dropdown-item>
                              </el-popconfirm>
                            </el-dropdown-menu>
                          </el-dropdown>
                        </div>
                      </template>
                    </departRoleData>
                  </div>
                </el-tab-pane>
              </el-tabs>
          </div>
        </el-col>
      </el-row>
      <!-- 部门角色抽屉 -->
      <div class="drawer">
        <el-drawer
        title="部门角色权限配置"
        :visible.sync="drawer"
        :with-header="true"
        :show-close="false"
        class="Drawerfontsize"
        :before-close="handleClose"
        ref="drawer"
        >
          <div class="authority_box">
            <div class="authority_top">所拥有的权限：</div>
            <div class="authority_content">
              <el-tree
              class="filter-tree"
              :data="authoritytreeData"
              :props="defaultProps1"
              :default-expand-all="isExpand1"
              :inline="true"
              :expand-on-click-node="false"
              :check-on-click-node="false"
              :show-checkbox="true"
              ref="authoritytreeData"
              node-key="key"
              :current-node-key="authoritytreeNodeSelected"
              @node-click="authoritytreeDataClick"
              :default-checked-keys="authoritySelectedover"
              @check="authoritycheckboxCheck"
              >
              </el-tree> 
              <div class="blankSpace"></div>
            </div>
          </div>
          
          <div class="demo-drawer__footer">
              <el-dropdown @command="treeStatus" class="dropdown_btn">
                <el-button>树操作 <i class="el-icon-arrow-up"></i></el-button>
                <el-dropdown-menu slot="dropdown" style="width=100px">
                  <el-dropdown-item command="1">父子关联</el-dropdown-item>
                  <el-dropdown-item command="2">取消关联</el-dropdown-item>
                  <el-dropdown-item command="3">全部勾选</el-dropdown-item>
                  <el-dropdown-item command="4">取消全选</el-dropdown-item>
                  <el-dropdown-item command="5">展开所有</el-dropdown-item>
                  <el-dropdown-item command="6">合并所有</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

            
            <el-button @click="cancelForm()">取 消</el-button>
            <el-button type="primary" plain>仅保存</el-button>
            <el-button type="primary" @click="$refs.drawer.closeDrawer()" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
          </div>
        </el-drawer>
      </div>
      <!-- 弹窗 -->
      <el-dialog :title="addORedit==1?'新增':'编辑'" :visible.sync="dialogFormVisible" :show-close="false" :close-on-press-escape="false">
        <div class="form_box">
          <el-form :model="roleForm" :rules="roleRules" ref="roleForm" label-width="140px">
            <el-form-item label="部门角色名称：" prop="roleName">
              <el-input v-model="roleForm.roleName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="部门角色编码：" prop="roleCode">
              <el-input v-model="roleForm.roleCode" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="描述：">
              <el-input v-model="roleForm.description" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('roleForm')">关 闭</el-button>
          <el-button type="primary" @click="submitForm('roleForm',addORedit)">确 认</el-button>
        </div>
      </el-dialog>
    </div>
    
    
</template>
<script>
import departBasicData from "../../components/liangliang/departBasicData";
import departUserData from "../../components/liangliang/departUserData";
import departRoleData from "../../components/liangliang/departRoleData";
      
import {queryMyDeptTreeList,
        departUserList,
        departRoleList,
        departRoleListSearch,
        departRoleListCheck,
        editRoleData,
        addRoleData,
        deleteRoleData,
        deleteRoleDataAlone,
        queryTreeListForDeptRole,
        queryDeptRolePermission
       } from "@/api/departUserList";
    export default{
    name:"departUserList",
    watch: {
      filterText(val) {
        this.$refs.treedata.filter(val.trim());
      },
      // 监视当前选中节点
      authoritytreeNodeSelected(key){
          if (key.toString()) {
              this.$refs["authoritytreeData"].setCurrentKey(key);
          } else {
              this.$refs["authoritytreeData"].setCurrentKey(null);
          }
      },
    },
    data() {
      var validatePass =(rule, value, callback) => {
        let data = {
          fieldVal:value,
          dataId:this.roleForm.id
        }
        departRoleListCheck(data).then((res)=>{
          if(res.code == 500){
            callback(new Error(res.message));
          }else if(res.code == 200){
            callback();
          }
        })
      };
      return{ 
        loading: false,// 延迟动画
        isExpand1:true,
        authoritytreeData:[],//树形控件数据
        defaultProps1: {
            children: 'children',
            label: 'slotTitle'
        },
        authoritySelectedover:[],// 点到的复选框数组
        authoritytreeNodeSelected:"",// 目前被点击的节点
        drawer:false,
        multipleSelection:[],//被选择的节点所有行数据的数组
        tableNodeSelected:0,// 选择的节点数
        addORedit:0,// 确定键是编辑还是新增
        roleRules:{
          roleName:[{ required: true, message: '请输入部门角色名称!', trigger: 'blur' }],
          roleCode:[{validator:validatePass, trigger: 'change' }]
        },
        roleForm:{
          roleName:"",
          roleCode:"",
          description:"",
          id:""
        },// 弹窗数据 深拷贝
        dialogFormVisible:false,//部门角色弹窗默认关闭
        userDataSearch:"",// 用户信息搜索内容
        roleDataSearch:"",// 部门角色搜索内容
        treedataNodeid:"",// 当前点击的树形控件id
        roletableData:[],//部门角色数据
        roleheaderData:[
          {
            prop:"roleName",
            label:"部门角色名称",
          },
          {
            prop:"roleCode",
            label:"部门角色编码",
          },
          {
            prop:"departId_dictText",
            label:"部门",
          },
          {
            prop:"description",
            label:"备注",
          },
          {
            prop:"handle",
            label:"操作",
            width:"170",
            slot:true
          }
        ],// 部门角色表头
        activeName: 'third',
        pageNo:1,// 默认页数
        pageSize:10,// 默认一页的数据量
        total:null,// 默认的总共的
        defaultExpandedNode:["c6d7cb4deeac411cb3384b1b31278596"],//默认打开的节点
        filterText: '',
        treedata: [],// 左边盒子的所有数据
        defaultProps: {
          children: 'children',
          label: 'departName'
        }
      }
    },
    methods: {
      // 树操作方法
      treeStatus(key){
        let _self = this;
        if(key==1){

        }else if(key==2){

        }else if(key==3){
          
        }else if(key==4){
          
        }else if(key==5){
          
        }else if(key==6){
          
        }
      },
      handleClose(done) {
        if (this.loading) {
          return;
        }
        this.$confirm('确定要提交表单吗？')
          .then(_ => {
            this.loading = true;
            this.timer = setTimeout(() => {
              done();
              // 动画关闭需要一定的时间
              setTimeout(() => {
                this.loading = false;
              }, 400);
            }, 2000);
          })
          .catch(_ => {});
      },
      cancelForm() {
        this.loading = false;
        this.drawer = false;
        clearTimeout(this.timer);
      },
      // 获取权限树形控件默认选中的复选框数组
      DeptRolePermission(roleId){
        queryDeptRolePermission(roleId).then((res)=>{
          if(res.code == 0){
            this.authoritySelectedover = res.result;
          }
        })
      },
      // 获取权限树形控件数据
      TreeListForDeptRole(){
        queryTreeListForDeptRole(this.treedataNodeid).then((res)=>{
          if(res.code == 0){
            this.authoritytreeData = res.result.treeList;
          }
        })
      },
      // 点击单个复选框的内容
      authoritycheckboxCheck(a,b,c,d){
          console.log(a);
      },
      // 点击权限列表的节点文本
      authoritytreeDataClick(data1,data2,data3){
          console.log(data1);
      },
      // 单行删除接口
      deleteDepartRoleDataAlone(id){
        deleteRoleDataAlone(id).then((res)=>{
          if(res.code == 200){
            this.$message({
              message: res.message,
              type: "success",
            });
            this.multipleSelection.length = 0;
            this.getDepartRoleList(this.treedataNodeid);
          }
        })
      },
      // 批量删除接口
      deleteDepartRoleList(id){
        let data = [];
        for(let item of id){
          data.push(item.id);
        };
        deleteRoleData(data.join(',')).then((res)=>{
          console.log(res);
          if(res.code == 200){
            this.$message({
              message: res.message,
              type: "success",
            });
            this.multipleSelection.length = 0;
            this.getDepartRoleList(this.treedataNodeid);
          }
        })
      },
      // 删除 授权 单行删除
      async tableStatus(val,row){
        if(val == 1){
          this.$confirm(
            "确定要删除所选中的 " +
              this.multipleSelection.length +
              " 条数据?",
            "确认删除",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            this.deleteDepartRoleList(this.multipleSelection)
          }).catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
        };// 删除按钮
        if(val == 2){
          this.authoritySelectedover = [];
          this.authoritytreeData = [];
          await this.TreeListForDeptRole();
          await this.DeptRolePermission(row.id);
          this.drawer = true;
        };// 单行授权
        if(val == 3){
          // console.log(row);
          this.deleteDepartRoleDataAlone(row.id);
        }// 删除
      },
      //获取被点击的数组 
      getSelection(val){
        this.multipleSelection = val;
        this.tableNodeSelected = this.multipleSelection.length;
        // console.log(this.multipleSelection);
      },
      // 当前一页几条数据
      SizeChange(val){
        this.pageSize = val;
        this.getDepartRoleList(this.treedataNodeid);
      },
      // 当前第几页
      CurrentPageChange(val){
        this.pageNo = val;
        this.getDepartRoleList(this.treedataNodeid);
      },
      // 新增角色按钮
      roleAdd(){
        let _self =this;
        if(!this.treedataNodeid){
           this.$message.error('请选择一个部门');
        }else{
          _self.roleForm.roleName="";
          _self.roleForm.roleCode="";
          _self.roleForm.description = "";
          _self.roleForm.id = "";
          this.dialogFormVisible = true;
          this.$nextTick(()=>{
            this.$refs["roleForm"].clearValidate();
          })
        }
        this.addORedit = 1;
      },
      // 单行编辑
      roleEdit(row){
        console.log(row);
        this.dialogFormVisible = true;
        this.roleForm = JSON.parse(JSON.stringify(row));
        this.addORedit = 2;
      },
      // 添加接口
      addRole(){
        let data = this.roleForm;
        data.departId = this.treedataNodeid;
        console.log(data);
        addRoleData(data).then((res)=>{
          // console.log(res);
          if(res.code == 200){
            this.$message({
              message: res.message,
              type: "success",
            });
            this.getDepartRoleList(this.treedataNodeid);
          }
        })
      },
      // 编辑接口
      editRole(){
        let data = this.roleForm;
        editRoleData(data).then((res)=>{
          if(res.code == 200){
            this.$message({
              message: res.message,
              type: "success",
            });
            this.getDepartRoleList(this.treedataNodeid);
          }
        })
      },
      // 弹窗确定按钮
      submitForm(formName,statu) {
        let _self = this;
        if(statu ==1){
          this.$refs[formName].validate(async(valid) => {
            if (valid) {
              await this.addRole();
              _self.dialogFormVisible = false;
              await setTimeout(function(){
                _self.roleForm.roleName="";
                _self.roleForm.roleCode="";
                _self.roleForm.description = "";
                _self.roleForm.id = "";
              },50)
            } else {
                return false;
            }
          });
        }else if(statu == 2){
          this.$refs[formName].validate((valid) => {
            if (valid) {
              // console.log(_self.roleForm);
              this.editRole();
              _self.dialogFormVisible = false;
              setTimeout(function(){
                _self.roleForm.roleName="";
                _self.roleForm.roleCode="";
                _self.roleForm.description = "";
                _self.roleForm.id = "";
              },50)
            } else {
                return false;
            }
          });
        }
        
      },
      // 弹窗取消按钮
      resetForm(formName) {
        let _self = this;
        this.dialogFormVisible = false;
        setTimeout(function(){
          _self.roleForm.roleName="";
          _self.roleForm.roleCode="";
          _self.roleForm.description = "";
          _self.roleForm.id = "";
        },50)
      },
      // 重置
      roleReset(){
        this.roleDataSearch = "";
        this.getDepartRoleList(this.treedataNodeid);
      },
      // 搜索
      roleSearch(){
        let data={
          pageNo:this.pageNo,
          pageSize:this.pageSize,
          deptId:this.treedataNodeid,
          roleName:this.roleDataSearch.trim()
        }
        departRoleListSearch(data).then((res)=>{
          if(res.code==200){
            this.roletableData = res.result.records;
          }
        })
      },
      // 获取当前部门角色数据
      getDepartRoleList(id){
        let data={
          pageNo:this.pageNo,
          pageSize:this.pageSize,
          deptId:id
        }
        departRoleList(data).then((res)=>{
          if(res.code == 200){
            this.roletableData = res.result.records;
            this.pageNo = res.result.current;
            this.pageSize = res.result.size;
            this.total = res.result.total;
          }
        })
      },
      // 当前被选中的节点
      treeNodeSelected(a,b,c,d){
        console.log(a);
        // console.log(b);
        this.$refs.departBasicData.getDepartList(a,b.parent.data.title);
        this.treedataNodeid = a.id;
        this.getDepartRoleList(this.treedataNodeid);
      },
      // 搜索
      filterNode(value, treedata) {
          if (!value) return true;
          return treedata.departName.indexOf(value) !== -1;
      },
      // 获取树形控件数据
      getUserTreeData(){
        queryMyDeptTreeList().then((res)=>{
          if(res.code == 0){
            this.treedata = res.result;
          }
        })
      }
    },
    mounted(){
      // 初始加载获取树形控件数据
      this.getUserTreeData()
    },
    components:{
      departBasicData,
      departUserData,
      departRoleData
    }
  }
</script>
<style lang="less" scoped>
.content {
  margin-left: 12px;
  background-color: #f0f2f5;
  height: 800px;
  .drawer{
    .Drawerfontsize{
      .authority_box{
        margin-left: 18px;
        margin-top: 15px;
      }
      /deep/.el-drawer__header{
        font-size: 16px;
        padding: 16px;
        border-bottom: 1px solid #e8e8e8;
        margin-bottom: 0px;
      }
      .blankSpace{
        height: 60px;
      }
      .demo-drawer__footer{
        position: absolute;
        background: #fff;
        width: 100%;
        height: 60px;
        left: 0px;
        bottom: 0px;
        z-index: 999;
        padding-top: 10px;
        border-top: 1px solid #e8e8e8;
      }
    }
    
  }
  .bg-content {
    background-color: #fff;
    border-radius: 2px;
    padding: 35px 20px 25px 30px;
    .basicdata{
      margin: 0px;
      border: 1px solid #e8e8e8;
      padding: 60px 240px 60px 80px;
    }
    .roledata{
      margin: 25px 30px 0 25px;
      .addBtn{
        margin-right: 10px;
      }
      .search_box{
          margin-bottom: 25px;
          .input_box{
              width: calc(30%);
              margin-right: 30px;
          }
      }
      .editBtn{
        border-right: 1px solid #e8e8e8;
        padding-right: 10px;
        margin-right: 10px;
      }
      .el-dropdown-link {
        cursor: pointer;
        color: #409EFF;
      }
      /deep/ .el-table .el-table__cell{
        padding: 5px 0;
      }
    }
    .userdata{
      margin: 25px 30px 0 25px;
      .search_box{
          margin-bottom: 25px;
          .input_box{
              width: calc(30%);
              margin-right: 30px;
          }
      }
    }
  }
  .form_box{
   padding: 0px 115px 0px 40px;
  }
}

</style>